package com.wuyan.wurpc.registry;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.json.JSONUtil;
import com.wuyan.wurpc.config.RegistryConfig;
import com.wuyan.wurpc.model.ServiceMetaInfo;
import io.etcd.jetcd.*;
import io.etcd.jetcd.options.GetOption;
import io.etcd.jetcd.options.PutOption;
import io.etcd.jetcd.watch.WatchEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Etcd注册中心
 */
public class EtcdRegistry implements Registry{

    private static final Logger log = LoggerFactory.getLogger(EtcdRegistry.class);
    private Client client;

    private KV kvClient;

    /**
     * 本机注册的节点key集合(用于维护续期)
     */
    private final Set<String> localRegisterNodeKeySet = new HashSet<>();

    /**
     * 注册中心服务缓存
     */
    private final RegistryServiceCache registryServiceCache = new RegistryServiceCache();

    /**
     * 正在监听的key集合
     */
    private final Set<String> watchingKeySet = new ConcurrentHashSet<>();

    /**
     * 根节点
     */
    private static final String ETCD_ROOT_PATH = "/rpc/";
    @Override
    public void init(RegistryConfig registryConfig) {
        log.info("注册中心初始化");
        client = Client.builder()
                .endpoints(registryConfig.getAddress())
                .connectTimeout(Duration.ofMillis(registryConfig.getTimeout()))
                .build();
        kvClient = client.getKVClient();
        heartBeat();
        log.info("开启心跳检测成功");
    }

    @Override
    public void register(ServiceMetaInfo serviceMetaInfo) throws Exception {
        log.info("将服务注册至ETCD：{}",serviceMetaInfo);
        //创建Lease和KV客户端
        Lease leaseClient = client.getLeaseClient();

        //创建一个30s的租约
        long leaseId = leaseClient.grant(30).get().getID();

        //设置要存储的键值对
        String registerKey = ETCD_ROOT_PATH + serviceMetaInfo.getServiceNodeKey();
        ByteSequence key = ByteSequence.from(registerKey, StandardCharsets.UTF_8);
        ByteSequence value = ByteSequence.from(JSONUtil.toJsonStr(serviceMetaInfo), StandardCharsets.UTF_8);

        //将键值对与租约关联起来，并设置过期时间
        PutOption putOption = PutOption.builder().withLeaseId(leaseId).build();
        kvClient.put(key, value, putOption).get();
        log.info("注册至本地缓存");
        //添加节点信息到本地缓存
        localRegisterNodeKeySet.add(registerKey);
        log.info("注册ETCD完成");
    }

    @Override
    public void unRegister(ServiceMetaInfo serviceMetaInfo) {
        log.info("开始删除服务：{}",serviceMetaInfo);
        String registerKey = ETCD_ROOT_PATH + serviceMetaInfo.getServiceNodeKey();
        kvClient.delete(ByteSequence.from(registerKey,StandardCharsets.UTF_8));
        //从本地缓存删除
        log.info("删除本地服务缓存");
        localRegisterNodeKeySet.remove(registerKey);
        log.info("删除服务完成");
    }

    @Override
    public List<ServiceMetaInfo> serviceDiscovery(String serviceKey) {
        //优先从缓存获取服务
        log.info("本地缓存发现服务");
        List<ServiceMetaInfo> cachedServiceMetaInfoList = registryServiceCache.readCache();
        if(cachedServiceMetaInfoList != null){
            return cachedServiceMetaInfoList;
        }

        //前缀搜索，结尾一定要加'/'
        String searchPrefix = ETCD_ROOT_PATH + serviceKey;// + "/";
        log.info("本地缓存未发现服务，从ETCD发现，服务前缀：{}, key:{}",searchPrefix, serviceKey);
        try{
            //前缀查询
            GetOption getOption = GetOption.builder().isPrefix(true).build();
            List<KeyValue> keyValues = kvClient.get(
                            ByteSequence.from(searchPrefix, StandardCharsets.UTF_8),
                            getOption)
                    .get()
                    .getKvs();
            //解析服务信息
            log.info("发现服务开始解析：{}",keyValues);
            List<ServiceMetaInfo> serviceMetaInfoList = keyValues.stream()
                    .map(keyValue -> {
                        String key = keyValue.getKey().toString(StandardCharsets.UTF_8);
                        String value = keyValue.getValue().toString(StandardCharsets.UTF_8);
                        //监听key的变化
                        log.info("开始监听：key :{}, value: {}", key, value);
                        watch(key);
                        return JSONUtil.toBean(value, ServiceMetaInfo.class);
                    }).collect(Collectors.toList());
            log.info("发现服务serviceMetaInfoList：{}",serviceMetaInfoList);
            //写入服务缓存
            log.info("将服务写入本地缓存");
            registryServiceCache.writeCache(serviceMetaInfoList);
            return serviceMetaInfoList;
        } catch (Exception e){
            throw new RuntimeException("获取服务列表失败", e);
        }
    }

    @Override
    public void destroy() {
        System.out.println("当前节点下线");
        for(String key : localRegisterNodeKeySet){
            try{
                kvClient.delete(ByteSequence.from(key, StandardCharsets.UTF_8));
            }catch (Exception e){
                throw new RuntimeException(key + "节点下线失败");
            }
        }
        //释放资源
        log.info("开始关闭资源kvClient:{},Client:{}", kvClient, client);
        if(kvClient != null){
            kvClient.close();
        }
        if(client != null){
            client.close();
        }
    }

    @Override
    public void heartBeat() {
        //10s秒续签一次
        CronUtil.schedule("*/10 * * * * *", new Task() {

            @Override
            public void execute() {
                //遍历本节点所有key
                log.info("开始续签");
                for(String key : localRegisterNodeKeySet){
                    try{
                        List<KeyValue> keyValues = kvClient.get(ByteSequence.from(key, StandardCharsets.UTF_8))
                                .get().getKvs();
                        //节点已过期(需要重启节点才能重新注册
                        if(CollUtil.isEmpty(keyValues)){
                            continue;
                        }
                        //节点未过期
                        KeyValue keyValue = keyValues.get(0);
                        String value = keyValue.getValue().toString(StandardCharsets.UTF_8);
                        ServiceMetaInfo serviceMetaInfo = JSONUtil.toBean(value, ServiceMetaInfo.class);
                        register(serviceMetaInfo);
                        log.info("续签成功：{}",serviceMetaInfo);
                    }catch (Exception e){
                        throw new RuntimeException(key + "续签失败", e);
                    }
                }
            }
        });
        //支持秒级定时任务
        log.info("开启心跳检测，检测服务续期");
        CronUtil.setMatchSecond(true);
        CronUtil.start();
    }

    /**
     * 监听(消费端)
     */
    @Override
    public void watch(String serviceNodeKey) {
        log.info("开始监听 serviceNodeKey : {}", serviceNodeKey);
        Watch watchClient = client.getWatchClient();
        //之前未被监听
        boolean newWatch = watchingKeySet.add(serviceNodeKey);
        if(newWatch){
            watchClient.watch(ByteSequence.from(serviceNodeKey, StandardCharsets.UTF_8), response -> {
                for(WatchEvent event : response.getEvents()){
                    switch (event.getEventType()){
                        case DELETE:
                            log.info("清理注册服务缓存");
                            registryServiceCache.clearCache();
                            break;
                        case PUT:
                        default:
                            break;
                    }
                }
            });
        }
    }
}
